<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search mb15">
				<el-input v-model="state.tableData.param.search" size="default" placeholder="请输入菜品名字"
					style="max-width: 180px"> </el-input>
				<el-button size="default" type="primary" class="ml10" @click="getDishAll()">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddRole()">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增菜品
				</el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column prop="id" label="序号" width="60" />
				<el-table-column prop="name" label="菜品名" show-overflow-tooltip></el-table-column>

				<el-table-column label="菜品分类" show-overflow-tooltip>
					<template #default="scope">
						<div v-for="(item, index) in state.tableData.param.goodtype" :key=index>
							<span v-if="scope.row.foodTypeid === item.id">{{ item.nameType }}</span>
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="introduce" label="菜品介绍" show-overflow-tooltip></el-table-column>

				<el-table-column label="图片" show-overflow-tooltip>
					<template #default="scope">
						<div class="block">
							<el-image style="width: 50px; height: 50px; cursor: pointer;" :src="scope.row.photograph"
								:zoom-rate="1.2" :preview-src-list="[scope.row.photograph]" preview-teleported
								fit="cover" altr="Item Image"></el-image>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="price" label="价格" show-overflow-tooltip>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEditRole(scope.row)">修改</el-button>
						<el-button size="small" text type="primary" @click="deleteDish(scope.row)">删除</el-button>
					</template>

				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.tableData.param.pageNum"
				background v-model:page-size="state.tableData.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="state.tableData.total">
			</el-pagination>
		</div>



		<div class="system-role-dialog-container">
			<el-dialog :title="statses.dialog.title" v-model="statses.dialog.loads" width="769px">
				<el-form ref="roleDialogFormRef" :model="statses.ruleForm" size="default" label-width="90px">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品名称:">
								<el-input v-model="statses.ruleForm.name" placeholder="请输入菜品名称" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品分类:">
								<el-select v-model="statses.ruleForm.foodTypeid" placeholder="请选择菜品分类" clearable>
									<el-option v-for="foodType in state.tableData.param.goodtype" :key="foodType.id"
										:value="foodType.id" 
										:label="foodType.nameType" >
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品介绍:">
								<el-input v-model="statses.ruleForm.introduce" placeholder="请输入菜品介绍" class="w100" />
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="价格:">
								<el-input-number v-model="statses.ruleForm.price"
									@change="validate(statses.ruleForm.price)" placeholder="请输如价格" class="w100" />
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="图片:">
								<el-upload class="box" action=" http://localhost:8080/merchant/food/upload"
									:show-file-list="false" :on-success="handleAvatarSuccess"
									:before-upload="beforeAvatarUpload" :headers="customHeaders">
									<img v-if="statses.ruleForm.photograph" :src="statses.ruleForm.photograph"
										class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="caner()" size="default">取 消</el-button>
						<el-button type="primary" @click="updateDish()" size="default">修改</el-button>
					</span>
				</template>
			</el-dialog>
		</div>



		<div class="system-role-dialog-container">
			<el-dialog :title="statses.dialog.title" v-model="statses.dialog.load" width="769px">
				<el-form ref="roleDialogFormRef" :model="statses.ruleForm" size="default" label-width="90px">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品名称:">
								<el-input v-model="statses.ruleForm.name" placeholder="请输入菜品名称" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品分类:">
								<el-select v-model="statses.ruleForm.foodTypeid" placeholder="请选择菜品分类" clearable>
									<el-option v-for="foodType in state.tableData.param.goodtype" :key="foodType.id"
										:value="foodType.id" 
										:label="foodType.nameType" >
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>


						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜品介绍:">
								<el-input v-model="statses.ruleForm.introduce" placeholder="请输入菜品介绍" class="w100" />
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="价格:">
								<el-input-number v-model="statses.ruleForm.price"
									@change="validate(statses.ruleForm.price)" placeholder="请输如价格" class="w100" />
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="图片:">
								<el-upload class="box" action=" http://localhost:8080/merchant/food/upload"
									:show-file-list="false" :on-success="handleAvatarSuccess"
									:before-upload="beforeAvatarUpload" :headers="customHeaders">
									<img v-if="statses.ruleForm.photograph" :src="statses.ruleForm.photograph"
										class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="caner()" size="default">取 消</el-button>
						<el-button type="primary" @click="add()" size="default">新增</el-button>
					</span>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script setup lang="ts" name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useDishApi } from '/@/api/dish/index';


// 引入组件
const RoleDialog = defineAsyncComponent(() => import('/@/views/system/role/dialog.vue'));

// 定义变量内容
const roleDialogRef = ref();
const state = reactive<SysRoleState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			goodtype: [],
			search: '',
			pageNum: 1,
			pageSize: 10,
		},
	},
});

const statses = reactive({
	ruleForm: {
		name: "", // 菜品名称
		foodTypeid: '', // 菜品分类
		introduce: "", // 排序
		price: 0.00, // 起始时间
		photograph: "", // 结束时间
	},
	dialog: {
		loads: false,
		load: false,
		laoding: true,
		isShowDialog: false,
		type: '',
		title: '新增优惠券',
		submitTxt: '新增',
		updatatTxt: '修改',
	},
});


//获取token
let tes = JSON.parse(localStorage.getItem('user') || '{}');
const customHeaders = reactive({
	token: tes.data,
});

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	const data = [];
	for (let i = 0; i < 20; i++) {
		data.push({
			roleName: i === 0 ? '超级管理员' : '普通用户',
			roleSign: i === 0 ? 'admin' : 'common',
			describe: `测试角色${i + 1}`,
			sort: i,
			status: true,
			createTime: new Date().toLocaleString(),
		});
	}
	state.tableData.data = data;
	state.tableData.total = state.tableData.data.length;
	setTimeout(() => {
		state.tableData.loading = false;
	}, 500);
};
//获取菜品信息
const getDishAll = async () => {
	useDishApi().getDishAll({name:state.tableData.param.search,pageNum:state.tableData.param.pageNum,pageSize:state.tableData.param.pageSize} ).then(res => {
		state.tableData.data = res.data.records
		state.tableData.total = res.data.total
	})
}

//图片上传处理
const handleAvatarSuccess = (res: any, file: any) => {
	statses.ruleForm.photograph = res.data;
}
const beforeAvatarUpload = () => {
}
//获取所有菜品分类
const getFoodType = async () => {
	useDishApi().getFoodType().then(res => {
		state.tableData.param.goodtype = res.data;
	})
}

//修改菜品信息
const updateDish = async () => {
	useDishApi().update(statses.ruleForm).then(res => { 
		caner();
	})
}
//清空属性值
const caner = () => {
	statses.ruleForm = {
		name: "", // 优惠券名称
		foodTypeid: '', // 优惠额度
		introduce: "", // 排序
		price: 0.00, // 起始时间
		photograph: "", // 结束时间
	}
	statses.dialog.load = false
	statses.dialog.loads = false

}
//新增菜品信息
const add=async()=>{
	useDishApi().add(statses.ruleForm).then(res=>{
		caner();
		getDishAll();
	})
}
//删除菜品信息
const deleteDish = (row: any) => {
	console.log(row)
	useDishApi().delete(row).then(res => {
		getDishAll();
	})
}

//确保优惠额度大于零且保留两位小数
const validate = (val: number) => {
	if (val < 0) {
		ElMessage.error("输入优惠额度必须是数字且大于零，小数只保留两位小数");
		statses.ruleForm.price = 0
	} else {
		statses.ruleForm.price = Math.round(val * 100) / 100.00
	}
}

// 打开新增菜品窗口
const onOpenAddRole = () => {
	statses.ruleForm = {
		name: "", // 优惠券名称
		foodTypeid: '', // 优惠额度
		introduce: "", // 排序
		price: 0.00, // 起始时间
		photograph: "", // 结束时间
	}
	statses.dialog.load = true

};
// 打开修改弹窗
const onOpenEditRole = (row: any) => {
	statses.dialog.loads = true
	statses.ruleForm = row
};
// 删除角色
const onRowDel = (row: RowRoleType) => {
	ElMessageBox.confirm(`此操作将永久删除角色名称：“${row.roleName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			getTableData();
			ElMessage.success('删除成功');
		})
		.catch(() => { });
};


// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getDishAll();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getDishAll();
};
// 页面加载时
onMounted(() => {
	getDishAll()
	getFoodType()
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;

		.el-table {
			flex: 1;
		}
	}
}

.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.box {
	border: 5px #8c939d;
	/* 边框宽度、样式和颜色 */
	border-radius: 10px;
	/* 可选：圆角边框 */
	padding: 10px;
	/* 可选：内边距 */
	box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.3);
}
</style>
